package com.rtx.express.service.impl;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSON;
import com.doudian.open.api.logistics_newCreateOrder.LogisticsNewCreateOrderRequest;
import com.doudian.open.api.logistics_newCreateOrder.LogisticsNewCreateOrderResponse;
import com.doudian.open.api.logistics_newCreateOrder.data.EbillInfosItem;
import com.doudian.open.api.logistics_newCreateOrder.param.Address;
import com.doudian.open.api.logistics_newCreateOrder.param.Address_4_4;
import com.doudian.open.api.logistics_newCreateOrder.param.Contact;
import com.doudian.open.api.logistics_newCreateOrder.param.ItemsItem;
import com.doudian.open.api.logistics_newCreateOrder.param.LogisticsNewCreateOrderParam;
import com.doudian.open.api.logistics_newCreateOrder.param.OrderInfosItem;
import com.doudian.open.api.logistics_newCreateOrder.param.ReceiverInfo;
import com.doudian.open.api.logistics_newCreateOrder.param.SenderInfo;
import com.doudian.open.api.logistics_templateList.LogisticsTemplateListRequest;
import com.doudian.open.api.logistics_templateList.LogisticsTemplateListResponse;
import com.doudian.open.api.logistics_waybillApply.LogisticsWaybillApplyRequest;
import com.doudian.open.api.logistics_waybillApply.LogisticsWaybillApplyResponse;
import com.doudian.open.api.logistics_waybillApply.param.LogisticsWaybillApplyParam;
import com.doudian.open.api.logistics_waybillApply.param.WaybillAppliesItem;
import com.doudian.open.core.AccessToken;
import com.doudian.open.core.AccessTokenBuilder;
import com.doudian.open.core.GlobalConfig;
import com.rtx.api.annotation.RtxExpressApi;
import com.rtx.common.MD5Helper;
import com.rtx.edi.model.express.bo.ExpressBO;
import com.rtx.edi.model.express.po.PlExpressApi;
import com.rtx.edi.model.express.po.PlExpressResult;
import com.rtx.express.service.IExpressService;

@RtxExpressApi(expressApiName = "抖音小店")
@Service("快递接口DY")
public class DYExpressAPI  implements IExpressService{
	
	Logger log = LoggerFactory.getLogger(this.getClass());
	
	private static String dy_url="https://openapi-fxg.jinritemai.com";
	private static String access_token;
	private static String appkey="6992781207461168655";
	private static String appSecret="20abd925-bb94-4eb3-84b9-d6bb809c1610";

	
	public String dyTemplateList() {
		GlobalConfig.initAppKey(appkey);
		GlobalConfig.initAppSecret(appSecret);
		LogisticsTemplateListRequest request = new LogisticsTemplateListRequest();
		AccessToken token = AccessTokenBuilder.build(22443058l);
		LogisticsTemplateListResponse res =  request.execute(token);
		return JSON.toJSONString(res);
	}
	
	@Override
	public void callCreaterOrderAPI(ExpressBO bo) {
		PlExpressApi task =  bo.getExpressTask();
//		PlExpressApiConfig config =  bo.getExpressConfig();
		try {
			GlobalConfig.initAppKey(appkey);
			GlobalConfig.initAppSecret(appSecret);
			GlobalConfig.initHttpClientConnectTimeout(60);
			
			LogisticsNewCreateOrderRequest createOrderRequest = mappingToCreateOrder(bo);
			
			AccessToken token = AccessTokenBuilder.build(22443058l);
			
			LogisticsNewCreateOrderResponse res = createOrderRequest.execute(token);
			
			String code = res.getCode();
			
			if("10000".equals(code)){
				List<EbillInfosItem> ebill_infos = res.getData().getEbillInfos();
				if(ebill_infos != null && ebill_infos.size() > 0){
					EbillInfosItem ebillInfo = ebill_infos.get(0);
					bo.setCallCreateOrderAPIResult("ok");
					PlExpressResult expressResult = bo.getExpressResultFillSendAndReceiver();
					expressResult.setExternorderkey(task.getExternorderkey());
					expressResult.setWaybillNo(ebillInfo.getTrackNo());
					//调用获取打印报文接口
					waybillApply(bo,ebillInfo.getTrackNo(),token);
					bo.setExpressResult(expressResult);
				}else{
					throw new RuntimeException(JSON.toJSONString(res));
				}
			}else{
				throw new RuntimeException(res.getMsg());
			}
			
		} catch (Exception e) {
			log.error("订单-"+task.getExternorderkey()+"-获取抖音快递单号失败：" + e.getMessage());
			bo.setMsg("订单-"+task.getExternorderkey()+"-获取抖音快递单号失败：" + e.getMessage());
		}
	}
	
	/**
	 * 
	 * @param bo
	 * @param trackNo
	 */
	private void waybillApply(ExpressBO bo,String trackNo,AccessToken token) {
		LogisticsWaybillApplyRequest request = new LogisticsWaybillApplyRequest();
		LogisticsWaybillApplyParam param = request.getParam();
		WaybillAppliesItem waybillApplies = new WaybillAppliesItem();
		waybillApplies.setLogisticsCode(bo.getExpressTask().getMappingCarriercode());
		waybillApplies.setTrackNo(trackNo);
		param.setWaybillApplies(Arrays.asList(waybillApplies));
		LogisticsWaybillApplyResponse response = request.execute(token);
		String code = response.getCode();
		if("10000".equals(code)){
			bo.getExpressResultFillSendAndReceiver().setPrintData(response.getData().getWaybillInfos().get(0).getPrintData());
			bo.getExpressResultFillSendAndReceiver().setSign(response.getData().getWaybillInfos().get(0).getSign());
		}else{
			bo.setMsg(response.getMsg());
			throw new RuntimeException(response.getMsg());
		}
	}
	
	/**
	 * https://op.jinritemai.com/docs/api-docs/16/1339
	 * @param bo
	 * @return
	 */
	private LogisticsNewCreateOrderRequest mappingToCreateOrder(ExpressBO bo) {
		PlExpressApi task = bo.getExpressTask();
		LogisticsNewCreateOrderRequest request = new LogisticsNewCreateOrderRequest();
		LogisticsNewCreateOrderParam param = request.getParam();
//		param.setDeliveryReq(null);
		param.setLogisticsCode(bo.getExpressConfig().getPlatformCarriercode());
		
		
		List<OrderInfosItem> orderInfos = new ArrayList<>();
		OrderInfosItem item = new OrderInfosItem();
		if(bo.getZdflag() == true) {
			item.setOrderId(task.getExternorderkey()+System.currentTimeMillis());
		}else {
			item.setOrderId(task.getExternorderkey());
		}
		
		
		
		item.setProductType(task.getProductCode());//产品类型
		
		ReceiverInfo receiverInfo =new ReceiverInfo();
		Address_4_4 address_4_4 = new Address_4_4();
		address_4_4.setCountryCode("CHN");
		address_4_4.setProvinceName(task.getReceiverProvince());
		address_4_4.setCityName(task.getReceiverCity());
		address_4_4.setDistrictName(task.getReceiverCounty());
		address_4_4.setDetailAddress(task.getReceiverAddress());
		address_4_4.setStreetName(task.getReceiverTown());
		receiverInfo.setAddress(address_4_4);
		Contact rcontact = new Contact();
		rcontact.setMobile(task.getReceiverMobile());
		rcontact.setName(task.getReceiverName());
		rcontact.setPhone(task.getReceiverPhone());
		receiverInfo.setContact(rcontact);
		
		item.setReceiverInfo(receiverInfo);
		
		////商品明细列表
		List<ItemsItem> list =new ArrayList<ItemsItem>();
		ItemsItem itemsItem = new ItemsItem();
		itemsItem.setItemName("服装");
		itemsItem.setItemCount(1);
		
		list.add(itemsItem);
		item.setItems(list);
		orderInfos.add(item);
		
		
		
		
		param.setOrderInfos(orderInfos);
		
		
		
		//发件人信息
		SenderInfo senderInfo = new SenderInfo();
		Address address = new Address();
		address.setCityName(task.getSendCity());
		address.setCountryCode("CHN");
		address.setDetailAddress(task.getSendAddress());
		address.setDistrictName(task.getSendCounty());
		address.setProvinceName(task.getSendProvince());
		address.setStreetName("");
		senderInfo.setAddress(address);
		
		Contact contact = new Contact();
		contact.setMobile(task.getSendMobile());
		contact.setPhone(task.getSendPhone());
		contact.setName(task.getSendName());
		senderInfo.setContact(contact);
		param.setSenderInfo(senderInfo);
		
		param.setUserId(-1L);
		param.setOrderChannel("54");
		return request;
	}
	
	

	@Override
	public void handleCreaterOrderAPIResponse(ExpressBO bo) {
		// TODO Auto-generated method stub
		
	}
	
	
	public String getparameter()  {
		
		GlobalConfig.initAppKey(appkey);
		GlobalConfig.initAppSecret(appSecret);
		
		AccessToken token = AccessTokenBuilder.build(22443058l);
		String accesstoken = token.getAccessToken();
		String app_key = appkey;	
		String method = "logistics.getShopKey";
		String param_json ="{}";
		String timestamp =new SimpleDateFormat("yyy-MM-dd HH:mm:ss").format(new Date());
		String v ="2";
		String sign =  MD5Helper.encryptMD5And16Hex(appSecret + "app_key" + appkey + "method" + method + "param_json" + param_json + "timestamp" + timestamp + "v2" + appSecret);
		String sign_method ="md5";

		String params = "access_token="+accesstoken+"&app_key="+app_key+"&method="+method+"&param_json="+param_json+"&timestamp="+timestamp+"&v="+v+"&sign="+sign+"&sign_method="+sign_method;

		return params;

	}
	
}
